package crawler;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;



public class UserManager {
    private static final String USER_FILE = "users.txt";
    private static final String REMEMBER_USER_FILE = "remember.users.txt";
    private static final String DELIMITER = "|";

    public boolean register(String username, String password) throws Exception {
        if (userExists(username)) {
            return false;
        }
        String hash = hashPassword(password);
        // 确保文件所在目录存在
        File file = new File(USER_FILE);
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            if (!parentDir.mkdirs()) {
                throw new IOException("无法创建目录: " + parentDir.getAbsolutePath());
            }
        }
        // 如果文件不存在则创建
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new IOException("无法创建文件: " + file.getAbsolutePath());
            }
        }
        try (PrintWriter out = new PrintWriter(new FileWriter(USER_FILE, true))) {
            out.println(username + DELIMITER + hash);
        }
        return true;
    }

    public boolean login(String username, String password) throws Exception {
        // 确保文件存在
        File file = new File(USER_FILE);
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new IOException("无法创建文件: " + file.getAbsolutePath());
            }
        }
        try (Scanner scanner = new Scanner(new File(USER_FILE))) {
            while (scanner.hasNextLine()) {
                String[] parts = scanner.nextLine().split("\\" + DELIMITER);
                if (parts[0].equals(username) && parts[1].equals(hashPassword(password))) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean userExists(String username) throws FileNotFoundException {
        // 检查用户是否存在
        try (Scanner scanner = new Scanner(new File(USER_FILE))) {
            while (scanner.hasNextLine()) {
                String[] parts = scanner.nextLine().split("\\" + DELIMITER);
                if (parts[0].equals(username)) {
                    return true;
                }
            }
        }
        return false;
    }

    private String hashPassword(String password) throws Exception {
        // SHA-256哈希实现
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] encodedHash = digest.digest(
                password.getBytes(StandardCharsets.UTF_8));
        StringBuilder hexString = new StringBuilder(2 * encodedHash.length);
        for (byte b : encodedHash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public void rememberPassword(String username) throws Exception {
        File file = new File(REMEMBER_USER_FILE);
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new IOException("无法创建文件: " + file.getAbsolutePath());
            }
        }

        try (PrintWriter out = new PrintWriter(new FileWriter(REMEMBER_USER_FILE, true))) {
            out.println(username);
        }
    }

    public void cancelRemember(String username) throws Exception {
        File file = new File(REMEMBER_USER_FILE);
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new IOException("无法创建文件: " + file.getAbsolutePath());
            }
        }

        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(REMEMBER_USER_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.equals(username)) {
                    lines.add(line);
                }
            }
        }
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(REMEMBER_USER_FILE))) {
            for (String filteredLine : lines) {
                writer.write(filteredLine);
                // 写入换行符
                writer.newLine();
            }
        }
    }

    public boolean isRemember(String username) throws Exception {
        File file = new File(REMEMBER_USER_FILE);
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new IOException("无法创建文件: " + file.getAbsolutePath());
            }
        }

        try (Scanner scanner = new Scanner(new File(REMEMBER_USER_FILE))) {
            while (scanner.hasNextLine()) {
                String[] parts = scanner.nextLine().split("\\" + DELIMITER);
                if (parts[0].equals(username)) {
                    return true;
                }
            }
        }
        return false;
    }

}

